//
//  SessionTableViewCell.m
//  zhixinApp
//
//  Created by zhiguanzhl on 2017/11/14.
//  Copyright © 2017年 zhiguanzhl. All rights reserved.
//

#import "SessionTableViewCell.h"
#import "UIImageView+EMWebCache.h"
#import "HeadButton.h"
#define kHaveUnreadAtMessage    @"kHaveAtMessage"
#define kAtYouMessage           1
#define kAtAllMessage           2

@implementation SessionTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    ViewRadius(self.headButton, 48*0.5);
    NSData *data = [[NSUserDefaults standardUserDefaults]valueForKey:@"numberArr"];
    _numberSArr = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _contentL.attributedText = [self latestMessageTitleForConversationModel:_model];
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.userInteractionEnabled = YES;
        self.accessoryView = nil;
        self.editingAccessoryView = nil;
        self.shouldIndentWhileEditing = NO;
    }
    return self;
}

+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *cellID = @"SessionTableViewCell";
    SessionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"SessionTableViewCell" owner:self options:nil].lastObject;
    }
    return cell;
}
- (NSAttributedString *)latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    NSString *timeStr = [NSString stringWithFormat:@"%lld",lastMessage.localTime];
    NSString *str = [Tool timeWithTimeIntervalString:(NSString *)timeStr];
    _timeL.text = str;
    
    if (conversationModel.conversation.type == 0) {
        //单聊
        NSString *idName = conversationModel.conversation.conversationId;
        NSString *nameStr = [Tool getHeadNameWithArr:self.numberSArr withString:idName];
        _nikeL.text = nameStr;
        if (nameStr.length>2) {
           nameStr = [nameStr substringFromIndex:1];
        }
       
        [_headButton setTitle:nameStr forState:UIControlStateNormal];
        
        
        
    }
    if (conversationModel.conversation.type == 1){//群聊
        
        
        EMGroup *group = [EMGroup groupWithId:conversationModel.conversation.conversationId];
        if (group.subject) {
            _nikeL.text = group.subject;
        }else{
            _nikeL.text = group.groupId;
        }
        [_headButton setTitle:@"群" forState:UIControlStateNormal];
        
    }
    
    
    if (lastMessage) {
        NSString *latestMessageTitle = @"";
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                // 表情映射。
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
                if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                    latestMessageTitle = @"[动画表情]";
                }
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
        
        //        if (lastMessage.direction == EMMessageDirectionReceive) {
        //            NSString *from = lastMessage.from;
        //            UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:from];
        //            if (profileEntity) {
        //                from = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
        //            }
        //            latestMessageTitle = [NSString stringWithFormat:@"%@: %@", from, latestMessageTitle];
        //        }
        
        NSDictionary *ext = conversationModel.conversation.ext;
        if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtAllMessage) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
            
        }
        else if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtYouMessage) {
            latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
            [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
        }
        else {
            attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
        }
    }
    
    return attributedStr;
}
@end
